/**
 * https://leetcode-cn.com/problems/degree-of-an-array/
 */

var arr = [1,2,2,3,1,4,2];
// var arr = [1,2,2,3,1];

/**
 * @param {number[]} nums
 * @return {number}
 */
var findShortestSubArray = function(nums) {
  var map = new Map()
  for(var i=0;i<nums.length;i++) {
    var record = map.get(nums[i]);
    if (record) {
      record.distance = i - record.firstIndex + 1;
      record.lastIndex = i;
      record.times += 1;
    } else {
      record = {
        firstIndex: i,
        lastIndex: i,
        distance: 1,
        value: nums[i],
        times: 1
      }
      map.set(nums[i], record);
    }
  }
  console.log(map);
  var target;
  map.forEach(function(value, key) {
    if (!target) {
      target = value;
    } else {
      if (value.times > target.times) {
        target = value;
      } else if (value.times == target.times && value.distance < target.distance) {
        target = value;
      }
    }
  })
  // console.log(target);
  return target ? target.distance : 0;
};

var length = findShortestSubArray(arr);
console.log('数组的度', length);